#include "AsioIOServicePool.h"

AsioIOServicePool::~AsioIOServicePool()
{
	std::cout << "~AsioIOServicePool()" << std::endl;
}


AsioIOServicePool::AsioIOServicePool(size_t size) :_io_contexts(size), _works(size), _next_ioc(0),_size(size)
{
	for (int i = 0; i < size; i++) {
		_works[i] = std::unique_ptr<Work>(new Work(_io_contexts[i]));
	}

	for (int i = 0; i < size; i++) {
		_threads.emplace_back([this, i]() {
			_io_contexts[i].run();
			});
	}
}

boost::asio::io_context& AsioIOServicePool::getIOContext()
{
	boost::asio::io_context& ioc = _io_contexts[_next_ioc++];
	if (_next_ioc == _size) {
		_next_ioc = 0;
	}
	return ioc;
}

void AsioIOServicePool::stop()
{
	for (auto& work : _works) {
		work.get()->get_io_context().stop();
		work.reset();
	}
	for (auto& thread : _threads) {
		thread.join();
	}
}
